package com.ceba.test.modules.statistic.helper;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.ceba.base.dbdata.MysqlUtils;
import com.ceba.base.helper.LoggerHelper;
import com.ceba.cebautils.DateUtil;
import com.ceba.cebautils.StringUtil;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ceba.test.base.configs.CebaConfig;
import com.ceba.test.base.configs.CebaPathUtil;
import com.ceba.test.base.enums.LogOpTypeEnum;
import com.ceba.test.base.enums.LogTypeEnum;
import com.ceba.test.base.helper.SystemHelper;
import com.ceba.test.base.otherjar.httpclient.FormFieldKeyValuePair;
import com.ceba.test.base.otherjar.httpclient.HttpPostEmulator;
import com.ceba.test.base.otherjar.httpclient.UploadFileItem;
import com.ceba.test.modules.admin.logicService.AdminLogicService;
import com.ceba.test.modules.log.logicService.LogLogicService;
import com.ceba.test.modules.regist.entity.EnterpriseRegisterLog;
import com.ceba.test.modules.regist.logicService.RegistLogicService;
import com.ceba.test.modules.sign.logicService.SignLogicService;
import com.ceba.test.modules.statistic.entity.ReportSign;
import com.ceba.test.modules.statistic.logicService.StatisticLogicService;

import abc.ID;
import abc.util.DateUtils;
import configs.context.SpringBeans;


public class CollectSignHelper {
	static Logger logger = LoggerFactory.getLogger(CollectSignHelper.class);
	
	private static LogLogicService logLogicService = SpringBeans.getLogLogicService("logLogicService");
	private static StatisticLogicService statisticLogicService = SpringBeans.getStatisticLogicService("statisticLogicService");
	private static AdminLogicService adminLogicService = SpringBeans.getAdminLogicService("adminLogicService");
	private static SignLogicService signLogicService = SpringBeans.getSignLogicService("signLogicService");
	static ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
	private static RegistLogicService registLogicService = SpringBeans.getRegistLogicService("registLogicService");
	
	/**
	 * 读取所有签名文档个数
	 * @return
	 */
	@SuppressWarnings("unused")
	public static String getSignCount(){
		try {
			long allSC_R = statisticLogicService.getAllReportSign();
			long YSC_R =statisticLogicService.getYearReportSign();
			long allSC_A =  statisticLogicService.getAllAttachSign();
			long YSC_A = statisticLogicService.getYearAttachSign();
			
			long count = allSC_R+allSC_A;
			return ""+count;
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return "0";
		}
	}
	
	
	/**
	 * 只获取当前用户的签名份数
	 * 
	 * 
	 */
	public static String getCurUserSignCount(String userId,int editionType){
		try {
		long allSC_R = statisticLogicService.getAllUserReportSign(userId,editionType);
		return ""+allSC_R;
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return "0";
		}
	}
	
	
	
	/**
	 * 每次签名后，实时更新签名文档的个数到CebaConfig数据库，同时记录日志
	 * type  =1 报告  2 附件
	 * num   签名个数
	 * 更新全部签名报告个数，全部签名附件个数
	 * 更新今年全部签名报告个数YEAR_SIGNCOUNT_REPORT，今年全部签名附件个数YEAR_SIGNCOUNT_ATTACH
	 *    一年的第一天的0点，将YEAR_SIGNCOUNT_REPORT，YEAR_SIGNCOUNT_ATTACH清空，在定时器CollectSignTimeTask清空
	 *    当ALL_SIGNCOUNT_REPORT=0时，直接从cb_report_sign取值赋值
	 *    当YEAR_SIGNCOUNT_REPORT=0时，直接从cb_report_sign取今年签名的报告个数赋值
	 *    当ALL_SIGNCOUNT_ATTACH=0时，直接从cb_report_attach取值赋值
	 *    当YEAR_SIGNCOUNT_ATTACH=0时，直接从cb_report_attach取今年签名的附件个数赋值
	 *    当份数不一致时，标记
	 *       报告不一致，CebaConfig.signReportNotConsist标记
	 *       附件不一致，CebaConfig.signAttachNotConsist标记
	 */
	public static void updateSignCountToDb(ReportSign  parm ){
		if(parm.getNum() <=0){
			return ;
		}
		try {
			if(parm.getFileType()==1 ){
				String allSc_Rs = CebaConfig.getDecode(CebaConfig.get("ALL_SIGNCOUNT_REPORT"));
				long allSC_R = StringUtil.isEmptyString(allSc_Rs)?0:Long.valueOf(allSc_Rs);
				if(allSC_R==0){
					long countR = signLogicService.getAllSignReports();
					allSC_R = countR;
				}else{
					allSC_R += parm.getNum();
				}
				String ySc_Rs = CebaConfig.getDecode(CebaConfig.get("YEAR_SIGNCOUNT_REPORT"));
				long YSC_R =StringUtil.isEmptyString(ySc_Rs)?0:Long.valueOf(ySc_Rs);
				
				if(YSC_R==0){
					long countYR = signLogicService.getYearSignReports();
					YSC_R = countYR;
				}else{
					YSC_R += parm.getNum();
				}
				CebaConfig.set("ALL_SIGNCOUNT_REPORT", CebaConfig.getEncode(allSC_R+""));
				CebaConfig.set("YEAR_SIGNCOUNT_REPORT",  CebaConfig.getEncode(YSC_R+""));
				logger.info("签名"+parm.getNum()+"份文档，文档名称为"+parm.getFileName()
							+ ";ALL_SIGNCOUNT_REPORT ="+allSC_R+";YEAR_SIGNCOUNT_REPORT="+YSC_R);
			}else if(parm.getFileType()==2 ){ //附件
				String allSc_As = CebaConfig.getDecode(CebaConfig.get("ALL_SIGNCOUNT_ATTACH"));
				long allSC_A =  StringUtil.isEmptyString(allSc_As)?0:Long.valueOf(allSc_As);
				if(allSC_A==0){
					long countAR = signLogicService.getAllSignOReports();
					allSC_A = countAR;
				}else{
					allSC_A = allSC_A + parm.getNum();
				}
				String ySc_As = CebaConfig.getDecode(CebaConfig.get("YEAR_SIGNCOUNT_ATTACH"));
				long YSC_A = StringUtil.isEmptyString(ySc_As)?0:Long.valueOf(ySc_As);
				if(YSC_A==0){
					long countYAR = signLogicService.getYearSignOReports();
					YSC_A = countYAR;
				}else{
					YSC_A += parm.getNum();
				}
				CebaConfig.set("ALL_SIGNCOUNT_ATTACH",  CebaConfig.getEncode(allSC_A+""));
				CebaConfig.set("YEAR_SIGNCOUNT_ATTACH", CebaConfig.getEncode( YSC_A+""));
				logger.info("签名"+parm.getNum()+"份附件,文件名为"+parm.getFileName()
							+ ";ALL_SIGNCOUNT_ATTACH ="+allSC_A+";YEAR_SIGNCOUNT_ATTACH="+YSC_A);
			}
			if(parm.getFileType()==1 || parm.getFileType()==2){
				//获取允许签名的份数
				String allSignNumS = CebaConfig.getDecode(CebaConfig.get("ALLOW_SIGN_NUM"));
				long allSignNum = StringUtil.isEmptyString(allSignNumS)?0:Long.valueOf(allSignNumS);
				allSignNum = allSignNum -parm.getNum();
				CebaConfig.set("ALLOW_SIGN_NUM",  CebaConfig.getEncode(allSignNum+""));
				logger.info("剩余允许签名的份数="+allSignNum);
			}
			if(parm.getFileType()==3 ){//未签名
				String today = DateUtil.getNowTime(DateUtil.YYYY_MM_DD_HH_MM_SS);
				StringBuffer logS = new StringBuffer();
				long allSC_R = statisticLogicService.getAllReportSign();
				long YSC_R =statisticLogicService.getYearReportSign();
				long allSC_A =  statisticLogicService.getAllAttachSign();
				long YSC_A = statisticLogicService.getYearAttachSign();
				long Other_A = logLogicService.getAllNoSignFileCount();
				logS.append(today+"记录: ")
				.append("其他文件"+parm.getFileName()+" 1份，共"+Other_A+"份;")
				.append("今年报告签名"+YSC_R+"份,附件签名"+YSC_A+"份;")
				.append("全部报告签名"+allSC_R+"份,附件签名"+allSC_A+"份;");
				logLogicService.addLog(LogTypeEnum.SIGN_LOGTYPE.getType(), 
						LogOpTypeEnum.SIGN_NO_NEED.getType(), logS.toString(), "","");
				logger.info(logS.toString());
			}
			CebaConfig.updateSignInfo();
		} catch (Exception e) {
			LoggerHelper.error(logger, e,"更新签名文档错误");
		}
	}
	
	/**
	 * 备份本地数据库同时上传数据库到阿里云
	 */
	public static void backupSql(){
		cachedThreadPool.execute(new Runnable() {
			public void run() {
				try{
					String filePath =  CebaPathUtil.getDBBackPath()+"/"+DateUtils.formatDate(new Date())+"/"+ID.getGuid()+".sql";
					if(!adminLogicService.backupDatabase(filePath)){
						logger.info("备份数据库失败，无法同步数据库，请联系ceba！");
					}
				}catch(Exception e){
					LoggerHelper.error(e, "");
				}
			}
		});
	}
	
	/**
	 * 备份本地签名份数数据上传数据库到阿里云
	 * @param url
	 */
	public static void uploadToServer(String url, String enterpriseName){
		try {
			final String eName = CebaConfig.getDecode(enterpriseName);
			cachedThreadPool.execute(new Runnable() {
				public void run() {
					try{
						String name = "--"+eName+"--"+DateUtil.getNowTime(DateUtil.YYYYMMDDHHMMSSS);
						String sendName = "--"+enterpriseName+"--"+DateUtil.getNowTime(DateUtil.YYYYMMDDHHMMSSS);
						String filePath =  CebaPathUtil.getDBBackPath()+"/"+DateUtil.getNowTime(DateUtil.YYYY_MM_DD_)+"/"+name+".tt";
						if(!MysqlUtils.backupSignData(filePath,"config cb_report_sign cb_report_attach")){
							logger.info("备份签名数据库失败");
						}
						//filePath = URLEncoder.encode(filePath,"utf-8");
						// 设定要上传的普通Form Field及其对应的value
						ArrayList<FormFieldKeyValuePair> ffkvp = new ArrayList<FormFieldKeyValuePair>();
						ffkvp.add(new FormFieldKeyValuePair("fileName", sendName));//其他参数
						
						// 设定要上传的文件
						ArrayList<UploadFileItem> ufi = new ArrayList<UploadFileItem>();
						ufi.add(new UploadFileItem("tt", filePath));
						String response = "";
						try {
							response = HttpPostEmulator.sendHttpPostRequest(url, ffkvp, ufi);
							JSONObject json = new JSONObject(response);
							if(json.has("result") && json.getBoolean("result")){
								logger.info("upload ok");	
							}
						} catch (Exception e) {
							logger.error("upload error");
						}
						
					}catch(Exception e){
						LoggerHelper.error(e, "");
					}
				}
			});
		} catch (Exception e) {
			logger.error("upload error");
		}
	}
	
	/**
	 * 上一次导入到现在签名的剩余份数
	 * @return
	 */
	public static  int getLastUpdateToNowLeftSign(){
		try {
			List<EnterpriseRegisterLog> elogs = registLogicService.getEnterpriseRegisterLogList(SystemHelper.getSystemFeeType());
			if(elogs !=null && elogs.size() >0){
				EnterpriseRegisterLog log = elogs.get(0);
				//查询从上一次导入到现在签名的份数
				int counts= statisticLogicService.getAllStatistisCount(log.getCreateTime(),
						DateUtil.getNowTime(DateUtil.YYYY_MM_DD_HH_MM_SS), "");
				int newSignCount = Integer.valueOf(log.getNewSignCount());
				int lastSignCount = newSignCount - Integer.valueOf(counts);
				if(lastSignCount <0){
					lastSignCount = 0;
				}
			}
		} catch (Exception e) {
			LoggerHelper.error(e, "");
		}
		return 0;
	}
}
